﻿using MDK.Common;
using System.Threading;

namespace MDK.Device.Components
{
    public interface ISwitch : IPlcDeviceComponent
    {
        bool IsOn();

        void TurnOn();
        void TurnOff();
    }

    public class Switch : ISwitch
    {
        public IPlcDevice Device { get; }

        public PlcAddress Addr { get; private set; }

        public bool OnValue { get; set; }

        public Switch(IPlcDevice device, PlcAddress address, bool onValue = true)
        {
            Device = device;
            Addr = address;
            OnValue = onValue;
        }

        public bool IsOn()
        {
            return Device.PLC.BitIsSet(Addr);
        }

        public void TurnOn()
        {
            if (OnValue)
            {
                Device.PLC.SetBit(Addr);
            }
            else
            {
                Device.PLC.ResetBit(Addr);
            }
            HandoverData.SandStateChangeData(EnumCmdCode.OtherAction, ((MitsubishiPlc)Device.PLC).PlcIP, this.GetType().Name, Addr.ToString(), 1);
        }

        public void TurnOff()
        {
            if (OnValue)
            {
                Device.PLC.ResetBit(Addr);
            }
            else
            {
                Device.PLC.SetBit(Addr);
            }
            HandoverData.SandStateChangeData(EnumCmdCode.OtherAction, ((MitsubishiPlc)Device.PLC).PlcIP, this.GetType().Name, Addr.ToString(), 0);
        }
    }

    public class DoubleBitSwitch : ISwitch
    {
        public IPlcDevice Device { get; }

        public PlcAddress OnAddr { get; private set; }
        public PlcAddress OffAddr { get; private set; }

        private bool _isOn = false;

        private int SwitchTime { get; set; }

        public DoubleBitSwitch(IPlcDevice device, PlcAddress onAddr, PlcAddress offAddr, int switchTime = 150)
        {
            Device = device;
            OnAddr = onAddr;
            OffAddr = offAddr;
            SwitchTime = switchTime;
        }

        public bool IsOn()
        {
            return _isOn;
        }

        public void TurnOn()
        {
            Device.PLC.ResetBit(OnAddr);
            Device.PLC.ResetBit(OffAddr);
            Device.PLC.SetBit(OnAddr);
            Thread.Sleep(SwitchTime);
            _isOn = true;
        }

        public void TurnOff()
        {
            Device.PLC.ResetBit(OnAddr);
            Device.PLC.ResetBit(OffAddr);
            Device.PLC.SetBit(OffAddr);
            Thread.Sleep(SwitchTime);
            _isOn = false;
        }
    }
}